package cn.tedu.ivos.base.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

/**
 * 自定义认证类，用余处理自定义的认证逻辑
 */
@Service
@Slf4j
public class CustomAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private CustomUserDetailsService userDetailsService;
    /**
     * 用于用户认证
     * @param authentication
     * @return 用户认证的信息，包含用户名和密码等
     * @throws AuthenticationException 如果认证失败，抛出异常
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //从authentication对象中获取用户名和密码
        String username = authentication.getPrincipal().toString();
        String password = authentication.getCredentials().toString();
        //从用户详情业务类中获取用户详情
        //UserDetails是SpringSecurity框架规定的用户存储用户信息的类
        UserDetails userInfo = userDetailsService.loadUserByUsername(username);
        //检查密码是否正确，不正确抛出异常
        if(!userInfo.getPassword().equals(password))
            throw new BadCredentialsException("用户名或密码不正确，请重试");
        //如果认证通过，返回新的认证令牌  token
        return new UsernamePasswordAuthenticationToken(userInfo,password,userInfo.getAuthorities());
    }

    /**
     * 指定本提供者支持的认证类型
     * @param authentication   判断是否支持的认证类型
     * @return true 支持该认证类型
     */
    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }
}
